package com.ruoyi.app.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.json.JSONUtil;
import com.ruoyi.app.domain.AppImGroup;
import com.ruoyi.app.domain.AppImGroupApply;
import com.ruoyi.app.domain.AppImGroupJoinLog;
import com.ruoyi.app.domain.AppUser;
import com.ruoyi.app.domain.bo.AppImGroupApplyBo;
import com.ruoyi.app.domain.vo.AppImGroupApplyVo;
import com.ruoyi.app.mapper.AppImGroupApplyMapper;
import com.ruoyi.app.mapper.AppImGroupJoinLogMapper;
import com.ruoyi.app.mapper.AppImGroupMapper;
import com.ruoyi.app.mapper.AppUserMapper;
import com.ruoyi.app.service.IAppImGroupApplyService;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.domain.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.im.core.TxImTemplate;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * 群组申请Service业务层处理
 *
 * @author ruoyi
 * @date 2025-11-17
 */
@RequiredArgsConstructor
@Service
public class AppImGroupApplyServiceImpl implements IAppImGroupApplyService {

    private final AppImGroupApplyMapper baseMapper;
    private final AppImGroupMapper appImGroupMapper;
    private final AppUserMapper appUserMapper;
    private final TxImTemplate txImTemplate;
    private final AppImGroupJoinLogMapper appImGroupJoinLogMapper;

    /**
     * 查询群组申请
     */
    @Override
    public AppImGroupApplyVo queryById(Long id){
        return baseMapper.selectVoById(id);
    }

    /**
     * 查询群组申请列表
     */
    @Override
    public TableDataInfo<AppImGroupApplyVo> queryPageList(AppImGroupApplyBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<AppImGroupApply> lqw = buildQueryWrapper(bo);
        Page<AppImGroupApplyVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        if (CollUtil.isNotEmpty(result.getRecords())){
            for (AppImGroupApplyVo record : result.getRecords()) {
                AppUser appUser = appUserMapper.selectById(record.getUserId());
                if (appUser != null){
                    record.setUserName(appUser.getNickName());
                    record.setUserAvatar(appUser.getAvatar());
                    record.setTime(formatDate(record.getCreateTime()));
                }
            }
        }
        return TableDataInfo.build(result);
    }

    public static String formatDate(Date date) {
        if (date == null) return "";

        Calendar input = Calendar.getInstance();
        input.setTime(date);

        Calendar now = Calendar.getInstance();

        // 今天
        if (isSameDay(input, now)) {
            return new java.text.SimpleDateFormat("HH:mm").format(date);
        }

        // 昨天
        Calendar yesterday = Calendar.getInstance();
        yesterday.add(Calendar.DAY_OF_YEAR, -1);
        if (isSameDay(input, yesterday)) {
            return new java.text.SimpleDateFormat("MM-dd HH:mm").format(date);
        }

        // 今年
        if (input.get(Calendar.YEAR) == now.get(Calendar.YEAR)) {
            return new java.text.SimpleDateFormat("MM-dd HH:mm").format(date);
        }

        // 去年及更早
        return new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm").format(date);
    }

    private static boolean isSameDay(Calendar c1, Calendar c2) {
        return c1.get(Calendar.YEAR) == c2.get(Calendar.YEAR)
                && c1.get(Calendar.DAY_OF_YEAR) == c2.get(Calendar.DAY_OF_YEAR);
    }


    /**
     * 查询群组申请列表
     */
    @Override
    public List<AppImGroupApplyVo> queryList(AppImGroupApplyBo bo) {
        LambdaQueryWrapper<AppImGroupApply> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<AppImGroupApply> buildQueryWrapper(AppImGroupApplyBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<AppImGroupApply> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getUserId() != null, AppImGroupApply::getUserId, bo.getUserId());
        lqw.eq(bo.getGroupId() != null, AppImGroupApply::getGroupId, bo.getGroupId());
        lqw.eq(StringUtils.isNotBlank(bo.getReason()), AppImGroupApply::getReason, bo.getReason());
        lqw.eq(bo.getApplySource() != null, AppImGroupApply::getApplySource, bo.getApplySource());
        lqw.eq(bo.getStatus() != null, AppImGroupApply::getStatus, bo.getStatus());
        return lqw;
    }

    /**
     * 新增群组申请
     */
    @Override
    public Boolean insertByBo(AppImGroupApplyBo bo) {
        AppImGroupApply add = BeanUtil.toBean(bo, AppImGroupApply.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改群组申请
     */
    @Override
    public Boolean updateByBo(List<Long> id) {
        LambdaQueryWrapper<AppImGroupApply> appImGroupApplyLambdaQueryWrapper = new LambdaQueryWrapper<>();
        appImGroupApplyLambdaQueryWrapper.in(AppImGroupApply::getId, id);
        List<AppImGroupApply> appImGroupApplies = baseMapper.selectList(appImGroupApplyLambdaQueryWrapper);
        if (!appImGroupApplies.isEmpty()){
            for (AppImGroupApply appImGroupApply : appImGroupApplies) {
                if (appImGroupApply != null){
                    if (appImGroupApply.getStatus()!= 0){
                        return false;
                    }
                    Long userId = appImGroupApply.getUserId();
                    String groupId = appImGroupApply.getGroupId();
                    appImGroupApply.setStatus(1L);
                    //调用im拉入群聊
                    txImTemplate.insertUserGroup(groupId, Collections.singletonList(userId.toString()));
                    if (baseMapper.updateById(appImGroupApply) > 0){
                        AppImGroup appImGroup = appImGroupMapper.selectOne(new LambdaQueryWrapper<AppImGroup>().eq(AppImGroup::getId, groupId));
                        if (appImGroup != null){
                            String member = appImGroup.getMember();
                            List<Long> members = JSONUtil.toList(member, Long.class);
                            members.add(userId);
                            member = JSONUtil.toJsonStr(members);
                            appImGroup.setMember(member);
                            appImGroupMapper.updateById(appImGroup);
                        }
                    }
                    //新增群组进退记录
                    AppImGroupJoinLog appImGroupJoinLog = new AppImGroupJoinLog();
                    appImGroupJoinLog.setUserId(userId);
                    appImGroupJoinLog.setGroupId(groupId);
                    appImGroupJoinLog.setActionType(1L);
                    appImGroupJoinLog.setSourceUserId(userId);
                    appImGroupJoinLogMapper.insert(appImGroupJoinLog);

                }
            }
        }

        return true;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(AppImGroupApply entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除群组申请
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }
}
